package cn.hongxin.sap.conn.utils;

import cn.getech.poros.framework.common.api.RestResponse;
import cn.hongxin.basic.business.client.ba.BaErpProdQueueClient;
import cn.hongxin.basic.business.client.erp.BaErpFunctionClient;
import cn.hongxin.basic.business.dto.ba.BaErpProdQueueDto;
import cn.hongxin.sap.conn.entity.ErpFunctionReturnVO;
import com.google.gson.Gson;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.*;

@Component
public class SapCommHelp {

    private static final Logger log = LoggerFactory.getLogger(SapCommHelp.class);

    @Autowired
    private BaErpProdQueueClient baErpProdQueueClient;

    /*@Qualifier("sapInterfaceJdbcTemplate")
    @Autowired
    private JdbcTemplate sapInterfaceJdbcTemplate;*/

    @Qualifier("sapConfigJdbcTemplate")
    @Autowired
    private JdbcTemplate sapConfigJdbcTemplate;

    private static Map<String, JdbcTemplate> customDataSources = new HashMap<String, JdbcTemplate>();
    @PostConstruct
    public void init() {
        customDataSources.put("sapConfig",sapConfigJdbcTemplate);
    }

    public JdbcTemplate getJdbcTemplate(String key){
        /*if(StringUtils.isEmpty(key)){//若没传数据库名或为null则取默认数据库
            key = "sapInterface";
        }

        JdbcTemplate jdbcTemplate = null;
        switch (key) {
            case "sapConfig": //特定操作
                jdbcTemplate = sapConfigJdbcTemplate;
               break;
            default:
                jdbcTemplate = sapInterfaceJdbcTemplate;
                break;
        }*/
       return sapConfigJdbcTemplate;
    }

    public Object[] batchInsert(List<Object[]> listObj, String[] tableColunmName, String tableName, String action, String where,String dataBaseName)
    {
        Object[] result = new Object[1];
        String returnColunm = ""; //要插入的列名
        String valueParam = ""; //要插入数据的参数
        String whereParam = ""; //更新条件
        //SqlParameter[] param = new SqlParameter[tableColunmName.length]; //参数
        Object[] param = new Object[tableColunmName.length];
        String sql = String.format("insert into %1$s ", tableName);
        List list = new ArrayList();
        try{
            if ("update".equals(action)){
                sql = String.format(" update %1$s set ", tableName);
//                int i = 0;
                if(listObj!=null&&listObj.size()>0) {
                    Object[] obj = listObj.get(0);
                    for (int idx = 0; idx < tableColunmName.length; idx++) {
                        String item = tableColunmName[idx];
                        if (item != null) {
                            returnColunm += item + "=?,";
                            //param[i] = new SqlParameter("@" + item, obj[i]);
                            list.add(obj[idx]);
                        }
//                    i++;
                    }
                }

                returnColunm = returnColunm.substring(0, returnColunm.length() - 1);
                sql += returnColunm;
                getJdbcTemplate(dataBaseName).batchUpdate(sql,listObj);// SqlHelper.ExecuteNonQuery(SqlHelper.getConnectionStringLocalTransaction(), CommandType.Text, sql, param);
            }else{
                ///#region "新增"
//                int i = 0;
                if(listObj!=null&&listObj.size()>0) {
                    Object[] obj = listObj.get(0);
                    for (int idx = 0; idx < tableColunmName.length; idx++) {
                        String item = tableColunmName[idx];
                        if (item != null) {
                            returnColunm += item + ",";
                            valueParam += "?,";
                            //param[i] = new SqlParameter("@" + item, obj[i]);
                            list.add(obj[idx]);
                        }
//                    i++;
                    }
                }
                returnColunm = " (" + returnColunm.substring(0, returnColunm.length() - 1) + ")";
                valueParam = valueParam.substring(0, valueParam.length() - 1);
                sql += returnColunm + " values(" + valueParam + ")";
                getJdbcTemplate(dataBaseName).batchUpdate(sql,listObj);//SqlHelper.ExecuteNonQuery(SqlHelper.getConnectionStringLocalTransaction(), CommandType.Text, sql, param);
            }
        }catch (Exception ex){
            ex.printStackTrace();
            result[0] = ex.getMessage();
        }
        return result;
    }

    public int insertlfdjorder(Object[] obj, String[] tableColunmName, String tableName, String action, String where,String dataBaseName)
    {
        int result = 0;
        String returnColunm = ""; //要插入的列名
        String valueParam = ""; //要插入数据的参数
        String whereParam = ""; //更新条件
        //SqlParameter[] param = new SqlParameter[tableColunmName.length]; //参数
        Object[] param = new Object[tableColunmName.length];
        String sql = String.format("insert into %1$s ", tableName);
        List list = new ArrayList();
        try{
            if ("update".equals(action)){
                sql = String.format(" update %1$s set ", tableName);
//                int i = 0;
                for (int idx = 0; idx < tableColunmName.length; idx++){
                    String item = tableColunmName[idx];
                    if (item != null){
                        returnColunm += item + "=?,";
                        //param[i] = new SqlParameter("@" + item, obj[i]);
                        list.add(obj[idx]);
                    }
//                    i++;
                }
                returnColunm = returnColunm.substring(0, returnColunm.length() - 1);
                if (StringUtils.isNotBlank(where)){
                    sql += returnColunm + where;
                }
                result = getJdbcTemplate(dataBaseName).update(sql,list.toArray());// SqlHelper.ExecuteNonQuery(SqlHelper.getConnectionStringLocalTransaction(), CommandType.Text, sql, param);
                int jj = 1/0;
            }else{
                ///#region "新增"
//                int i = 0;
                for (int idx = 0; idx < tableColunmName.length; idx++){
                    String item = tableColunmName[idx];
                    if (item != null){
                        returnColunm += item + ",";
                        valueParam += "?,";
                        //param[i] = new SqlParameter("@" + item, obj[i]);
                        list.add(obj[idx]);
                    }
//                    i++;
                }
                returnColunm = " (" + returnColunm.substring(0, returnColunm.length() - 1) + ")";
                valueParam = valueParam.substring(0, valueParam.length() - 1);
                sql += returnColunm + " values(" + valueParam + ")";
                result = getJdbcTemplate(dataBaseName).update(sql,list.toArray());//SqlHelper.ExecuteNonQuery(SqlHelper.getConnectionStringLocalTransaction(), CommandType.Text, sql, param);
            }
        }catch (Exception ex){
            log.error(ex.getMessage());
            ex.printStackTrace();
            throw ex;
        }
        return result;
    }


    //public int insertlfdjorder(Object[] obj, String[] tableColunmName, String tableName, String action, String where)
    public Object[] insertlfdjorder(Map<String, Object> map,Map<String,String> isMainKeyMap,String[] fieldNames, String tableName, String action,String where,String dataBaseName)
    {
        SapCommHelp commHelp = new SapCommHelp();
        Object[] result = new Object[2];
        result[0] = 0;
        result[1] = "";
        String returnColunm = ""; //要插入的列名
        String valueParam = ""; //要插入数据的参数
        Object[] param = new Object[fieldNames.length];
        String sql = String.format("insert into %1$s ", tableName);
        List list = new ArrayList();
        String sqlCondition = " where 1=1 ";
        int count = 0;
        //配置页面配置了主键才去数据库验证该记录是否存在
        if(isMainKeyMap!=null&&isMainKeyMap.size()>0){
            for(String keyName:isMainKeyMap.keySet()){
                String keyValue = isMainKeyMap.get(keyName);
                if("char".equals(keyValue)){
                    sqlCondition+=" and "+keyName+"='"+map.get(keyName)+"'";
                }else if("num".equals(keyValue)){
                    sqlCondition+=" and "+keyName+"="+Integer.valueOf(map.get(keyName)+"");
                }
            }
            //count = commHelp.executeProc(tableName+finalSqlCondition,getJdbcTemplate(dataBaseName));
            if("add".equals(action)){
                //插入前先根据主键查询数据是否存在，若已存在则更新
                count = getJdbcTemplate(dataBaseName).queryForObject("select count(*) from " + tableName + sqlCondition, Integer.class);
                //System.out.println("普通sql执行！！");
                if(count>0){
                    action = "update";
                }
            }
        }
        try{
            if ("update".equals(action)){
                sql = String.format(" update %1$s set ", tableName);
                String isMainKeyMapStr = "";
                if(isMainKeyMap!=null&&isMainKeyMap.size()>0){
                    isMainKeyMapStr = isMainKeyMap.toString();
                }
                for (int idx = 0; idx < fieldNames.length; idx++){
                    String item = fieldNames[idx];
                    if(item != null){
                        //如果查到该记录已存在，则更新时把对应的主键去掉
                        if(!isMainKeyMapStr.contains(item)){
                            returnColunm += item + "=?,";
                            list.add(map.get(fieldNames[idx]));
                        }

                    }
                }
                returnColunm = returnColunm.substring(0, returnColunm.length() - 1);
                sql += returnColunm + sqlCondition;

                if(StringUtils.isNotBlank(list.toString()))//若全部值为空则不插入
                result[0] = getJdbcTemplate(dataBaseName).update(sql,list.toArray());// SqlHelper.ExecuteNonQuery(SqlHelper.getConnectionStringLocalTransaction(), CommandType.Text, sql, param);
                //int jj = 1/0;
            }else{
                ///#region "新增"
//                int i = 0;
                for (int idx = 0; idx < fieldNames.length; idx++){
                    String item = fieldNames[idx];
                    if (item != null){
                        returnColunm += item + ",";
                        valueParam += "?,";
                        list.add(map.get(fieldNames[idx]));
                    }
                }
                returnColunm = " (" + returnColunm.substring(0, returnColunm.length() - 1) + ")";
                valueParam = valueParam.substring(0, valueParam.length() - 1);
                sql += returnColunm + " values(" + valueParam + ")";
                if(StringUtils.isNotBlank(list.toString()))//若全部值为空则不插入
                result[0] = getJdbcTemplate(dataBaseName).update(sql,list.toArray());//SqlHelper.ExecuteNonQuery(SqlHelper.getConnectionStringLocalTransaction(), CommandType.Text, sql, param);
            }
        }catch (Exception ex){
            log.error(ex.getMessage());
            result[1] = ex.getMessage();
        }
        return result;
    }

    public List<Map<String,Object>> queryList(String sql,String dataBaseName){
        return getJdbcTemplate(dataBaseName).queryForList(sql);
    }

    /*public Map<String,Object> queryForMap(String sql){
        try {
            return sapInterfaceJdbcTemplate.queryForMap(sql);
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }*/

    //获取记录数
    public int queryTableCount(String dataBaseName,String sql){
        try {
            return getJdbcTemplate(dataBaseName).queryForObject(sql, Integer.class);
        } catch (EmptyResultDataAccessException e) {
            return 0;
        }
    }

    public int insertProdQueue(ErpFunctionReturnVO returnVO, BaErpFunctionClient baErpFunctionClient,String functionid,String param,String prodQueueId){
        Integer result = null;
        String sql = "";
        try{
            String returnErr = returnVO.getReturnErr();
            if(StringUtils.isNotBlank(prodQueueId)){//prodQueueId不为空代表重试调用SAP接口，因此这里需要更新prod_queue表对应记录
                if(StringUtils.isNotBlank(returnErr)) {//存在错误信息
                    sql = "UPDATE ba_erp_prod_queue set isexec=-1,responsejson='"+returnErr+"',status='false',update_time=NOW() where id="+prodQueueId;
                }else{
                    sql = "UPDATE ba_erp_prod_queue set isexec=1,responsejson='成功',status='ture',update_time=NOW() where id="+prodQueueId;
                }
                result =(int)baErpFunctionClient.executeInsertSql(sql).getData();
            }else{
                BaErpProdQueueDto baErpProdQueueDto = new BaErpProdQueueDto();
                baErpProdQueueDto.setFunctionid(functionid);
                baErpProdQueueDto.setFunctionname(returnVO.getFunctionName());
                baErpProdQueueDto.setOperatetype("手动调用");
                baErpProdQueueDto.setUpdateTime(new Date());
                baErpProdQueueDto.setRequestjson(param);
                if(StringUtils.isNotBlank(returnErr)){//存在错误信息
                    baErpProdQueueDto.setResponsejson(returnErr);
                    baErpProdQueueDto.setIsexec("-1");
                    baErpProdQueueDto.setStatus("false");
//                    sql = "INSERT INTO ba_erp_prod_queue(functionid,functionname,requestjson,responsejson,isexec, operatetype, status, update_time,create_time)" +
//                            "VALUES('"+functionid+"','"+returnVO.getFunctionName()+"','"+param+"','"+returnErr+"','-1','手动调用','false',NOW(),NOW())";
                }else{
                    baErpProdQueueDto.setResponsejson(new Gson().toJson(returnVO));
                    baErpProdQueueDto.setIsexec("1");
                    baErpProdQueueDto.setStatus("true");
//                    sql = "INSERT INTO ba_erp_prod_queue(functionid,functionname,requestjson,responsejson,isexec, operatetype, status, update_time,create_time)" +
//                            "VALUES('"+functionid+"','"+returnVO.getFunctionName()+"','"+param+"','成功','1','手动调用','true',NOW(),NOW())";
                }
                 baErpProdQueueClient.addQueue(baErpProdQueueDto);
                 result = 1;
            }

        }catch(Exception e){
            log.info("更新轮询队列表出错："+e.getMessage());
        }
        return result;
    }


    //更新参数队列表
    public int updateProdQueue(String id, ErpFunctionReturnVO returnVO, BaErpFunctionClient baErpFunctionClient){
        String sql = "";
        try{

            String returnErr = returnVO.getReturnErr();
            if(StringUtils.isNotBlank(returnErr)){//存在错误信息
                sql = "update ba_erp_prod_queue set isexec='-1' ,status='false',operateType='查询接口调用',updatetime=NOW(), responsejson='失败',functionname='"+returnVO.getFunctionName()+"' where id="+id;
            }else{
                sql = "update ba_erp_prod_queue set isexec='1' ,status='true',operateType='查询接口调用',updatetime=NOW(), responsejson='成功',functionname='"+returnVO.getFunctionName()+"' where id="+id;
            }
        }catch(Exception e){
            log.info("更新轮询队列表出错："+e.getMessage());
        }
        return (int)baErpFunctionClient.executeUpdateSql(sql).getData();
    }

    /*public int insert(String sql){
        return sapInterfaceJdbcTemplate.update(sql);
    }*/

    public int insert(Map<String, Object> map,String[] fieldNames, String tableName, String action,String where,String dataBaseName)
    {
        int result = 0;
        String returnColunm = ""; //要插入的列名
        String valueParam = ""; //要插入数据的参数
        Object[] param = new Object[fieldNames.length];
        String sql = String.format("insert into %1$s ", tableName);
        List list = new ArrayList();
        try{
            if ("update".equals(action)){
                sql = String.format(" update %1$s set ", tableName);
//                int i = 0;
                for (int idx = 0; idx < fieldNames.length; idx++){
                    String item = fieldNames[idx];
                    if (item != null){
                        returnColunm += item + "=?,";
                        //param[i] = new SqlParameter("@" + item, obj[i]);
                        list.add(map.get(fieldNames[idx]));
                    }
//                    i++;
                }
                returnColunm = returnColunm.substring(0, returnColunm.length() - 1);
                if (StringUtils.isNotBlank(where)){
                    sql += returnColunm + where;
                }
                //getJdbcTemplate(dataBaseName).qu
                result = getJdbcTemplate(dataBaseName).update(sql,list.toArray());// SqlHelper.ExecuteNonQuery(SqlHelper.getConnectionStringLocalTransaction(), CommandType.Text, sql, param);
            }else{
                ///#region "新增"
//                int i = 0;
                for (int idx = 0; idx < fieldNames.length; idx++){
                    String item = fieldNames[idx];
                    if (item != null){
                        returnColunm += item + ",";
                        valueParam += "?,";
                        list.add(map.get(fieldNames[idx]));
                    }
                }
                returnColunm = " (" + returnColunm.substring(0, returnColunm.length() - 1) + ")";
                valueParam = valueParam.substring(0, valueParam.length() - 1);
                sql += returnColunm + " values(" + valueParam + ")";
                result = getJdbcTemplate(dataBaseName).update(sql,list.toArray());//SqlHelper.ExecuteNonQuery(SqlHelper.getConnectionStringLocalTransaction(), CommandType.Text, sql, param);
            }
        }catch (Exception ex){
            log.error(ex.getMessage());
            ex.printStackTrace();
            throw ex;
        }
        return result;
    }

}
